package com.roger.mybatisplus.demo.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.roger.mybatisplus.demo.dao.UsersMapper;
import com.roger.mybatisplus.demo.entity.Users;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class MyRealm extends AuthorizingRealm{
    @Autowired
    private UsersMapper usersMapper;

    //自定义授权方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    // 自定义认证方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        String username = token.getUsername();
        QueryWrapper<Users> wrapper = new QueryWrapper<Users>().eq("username" , username);

        Users users = usersMapper.selectOne(wrapper);

        if(users == null){
            throw new UnknownAccountException("账户不存在");
        }
        return new SimpleAuthenticationInfo(users, token.getPassword(), "myRealm");
    }
}
